import { listPagedDatasetAnnotationsBuild, createDatasetAnnotationBuild, updateDatasetAnnotationBuild, deleteDatasetAnnotationBuild } from "@api/dataset/annotation";
import { getDatasetAnnotationSubscribe, setDatasetAnnotationSubscribe, type ListDatasetAnnotationsParam, type CreateDatasetAnnotationParam, type UpdateDatasetAnnotationParam } from "@entity/dataset/annotation";
import { get as getVal } from "svelte/store";

export const listDatasetAnnotations = async (datasetCode: string, val: ListDatasetAnnotationsParam, append: boolean = false) => {
  let list = getVal(getDatasetAnnotationSubscribe(val.dataset_entry_id))
  const o = await listPagedDatasetAnnotationsBuild(datasetCode)(val);
  if (append) {
    list.rows.push(...o.rows)
    list.total = o.total;
  } else {
    list = o
  }
  setDatasetAnnotationSubscribe(val.dataset_entry_id, list);
};

export const createDatasetAnnotation = async (datasetCode: string, val: CreateDatasetAnnotationParam, syncToStore: boolean = false) => {
  const datasetAnnotation = await createDatasetAnnotationBuild(datasetCode)(val)
  if (syncToStore) {
    const o = getVal(getDatasetAnnotationSubscribe(val.entry_id))
    o.rows.push({...datasetAnnotation, my_annotation_flag: true})
    setDatasetAnnotationSubscribe(val.entry_id, o);
  }
  return datasetAnnotation;
}

export const updateDatasetAnnotation = async (datasetCode: string, entry_id: number, val: UpdateDatasetAnnotationParam, syncToStore: boolean = false) => {
  const datasetAnnotation = await updateDatasetAnnotationBuild(datasetCode)(val)
  if (syncToStore) {
    const o = getVal(getDatasetAnnotationSubscribe(entry_id))
    let idx = o.rows.findIndex(v => v.id === datasetAnnotation.id)
    // console.log('before updated:', idx, JSON.stringify(val))
    o.rows.splice(idx, 1, {...datasetAnnotation, my_annotation_flag: true})
    setDatasetAnnotationSubscribe(entry_id, o);
  }
  return datasetAnnotation;
}

export const deleteDatasetAnnotation = async (datasetCode: string, entry_id: number, val: any, syncToStore: boolean = false) => {
  const datasetAnnotation = await deleteDatasetAnnotationBuild(datasetCode)(val)
  if (syncToStore) {
    const o = getVal(getDatasetAnnotationSubscribe(entry_id))
    let idx = o.rows.findIndex(v => v.id === datasetAnnotation.id)
    o.rows.splice(idx, 1)
    setDatasetAnnotationSubscribe(entry_id, o);
  }
  return datasetAnnotation;
}